<template>
    <div class="ios-category-page">
        <div class="ios-container">
            <div class="ios-row">
                <!-- 左侧分类栏与筛选 -->
                <div class="ios-sidebar">
                    <!-- 单一面板包含所有筛选项 -->
                    <div class="ios-panel">
                        <!-- 商品分类部分 -->
                        <div class="panel-header">
                            <h3>商品分类</h3>
                        </div>
                        <div v-if="categoriesLoading" class="category-loading">
                            <el-skeleton :rows="6" animated />
                        </div>
                        <div v-else class="ios-category-list">
                            <div class="category-grid">
                                <div v-for="category in categories" :key="category.id"
                                :class="['ios-category-item', { active: activeCategory === category.id.toString() }]"
                                    @click="handleCategorySelect(category.id.toString())">
                                <div class="category-icon">
                                    <img 
                                        v-if="category.icon && typeof category.icon === 'string' && category.icon.startsWith('http')"
                                        :src="category.icon" 
                                        :alt="category.name + ' icon'" 
                                        style="width: 24px; height: 24px; object-fit: contain;"
                                    />
                                    <component v-else :is="getCategoryIconComponent(category.icon)" />
                                </div>
                                <span class="category-name">{{ category.name }}</span>
                            </div>
                            </div>
                        </div>
                        
                        <!-- 价格区间部分 -->
                        <div class="divider"></div>
                        <div class="filter-header">
                            <h3>价格区间</h3>
                        </div>
                        <div class="filter-section-compact">
                            <el-slider v-model="priceRange" range :min="0" :max="10000" :step="100"
                                :format-tooltip="formatPrice" @change="applyFilters" />
                            <div class="price-range-display">
                                <span>¥{{ priceRange[0] }}</span>
                                <span class="divider-text">-</span>
                                <span>¥{{ priceRange[1] }}</span>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- 右侧内容区 -->
                <div class="ios-main-content">
                    <!-- 苹果风格搜索和筛选栏 -->
                    <div class="ios-search-bar">
                        <div class="search-input-wrapper">
                            <el-input v-model="searchKeyword" placeholder="搜索商品" class="ios-search-input"
                                @keyup.enter="handleSearch">
                                <template #prefix>
                                    <el-icon>
                                        <Search />
                                    </el-icon>
                                </template>
                            </el-input>
                        </div>
                        <div class="filter-actions">
                            <!-- 学校筛选 - 修改为下拉式面板 -->
                            <div class="filter-dropdown">
                                <div class="filter-dropdown-header" @click="toggleSchoolDropdown">
                                    <el-icon class="school-icon"><School /></el-icon>
                                    <span>{{ schoolFilter || '选择学校' }}</span>
                                    <el-icon><ArrowDown /></el-icon>
                                </div>
                                <div class="filter-dropdown-content" v-if="showSchoolDropdown">
                                    <!-- 添加搜索输入框 -->
                                    <div class="search-input-container">
                                        <el-input 
                                            v-model="schoolSearchText" 
                                            placeholder="搜索学校" 
                                            clearable
                                            @input="filterSchools"
                                            @keyup.enter="applySchoolSearch"
                                        >
                                            <template #prefix>
                                                <el-icon><Search /></el-icon>
                                            </template>
                                        </el-input>
                                    </div>
                                    
                                    <div 
                                        class="filter-option" 
                                        :class="{ active: schoolFilter === '' }"
                                        @click="selectSchool('')"
                                    >
                                        全部学校
                                    </div>
                                    <div 
                                        v-for="school in filteredSchools" 
                                        :key="school.value" 
                                        class="filter-option" 
                                        :class="{ active: schoolFilter === school.value }"
                                        @click="selectSchool(school.value)"
                                    >
                                        {{ school.label }}
                                    </div>
                                </div>
                            </div>

                            <!-- 商品状态筛选 - 修改为下拉式面板 -->
                            <div class="filter-dropdown">
                                <div class="filter-dropdown-header" @click="toggleConditionDropdown">
                                    <span>{{ getConditionLabel() }}</span>
                                    <el-icon><ArrowDown /></el-icon>
                                </div>
                                <div class="filter-dropdown-content" v-if="showConditionDropdown">
                                    <div 
                                        class="filter-option"
                                        :class="{ active: conditionFilter.length === 0 }"
                                        @click="clearConditionFilter"
                                    >
                                        全部状态
                                    </div>
                                    <div 
                                        v-for="option in conditionOptions" 
                                        :key="option" 
                                        class="filter-option" 
                                        :class="{ active: conditionFilter.includes(option) }"
                                        @click="toggleConditionOption(option)"
                                    >
                                        <div class="option-with-check">
                                            <el-icon v-if="conditionFilter.includes(option)" class="check-icon"><Check /></el-icon>
                                            <span>{{ option }}</span>
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <!-- 排序方式 - 修改为下拉式面板 -->
                            <div class="filter-dropdown">
                                <div class="filter-dropdown-header" @click="toggleSortDropdown">
                                    <span>{{ getSortLabel() }}</span>
                                    <el-icon><ArrowDown /></el-icon>
                                </div>
                                <div class="filter-dropdown-content" v-if="showSortDropdown">
                                    <div 
                                        v-for="sort in sortOptions" 
                                        :key="sort.value" 
                                        class="filter-option" 
                                        :class="{ active: sortBy === sort.value }"
                                        @click="handleSortSelect(sort.value)"
                                    >
                                        {{ sort.label }}
                                    </div>
                                </div>
                            </div>

                            <div class="ios-filter-button" @click="resetAllFilters">
                                <el-icon>
                                    <Refresh />
                                </el-icon>
                                <span>重置筛选</span>
                            </div>
                        </div>
                    </div>

                    <!-- 标题和结果统计 -->
                    <div class="ios-content-header">
                        <h2>{{ currentCategory?.name || '全部商品' }}</h2>
                        <span v-if="loading" class="result-count">
                            <el-skeleton style="width: 100px" animated />
                        </span>
                        <span v-else class="result-count">共 {{ total }} 件商品</span>
                    </div>

                    <!-- 商品网格 - 苹果风格卡片 -->
                    <div v-if="loading" class="loading-container">
                        <el-skeleton :rows="5" animated />
                        <el-skeleton :rows="5" animated />
                        <el-skeleton :rows="5" animated />
                    </div>
                    <div v-else-if="products.length === 0" class="empty-container">
                        <el-empty description="暂无商品" />
                    </div>
                    <div v-else class="product-grid-container">
                        <div class="ios-product-grid">
                            <div v-for="product in filteredProducts" :key="product.id" class="ios-product-card"
                                @click="(event) => handleProductClick(product, event)">
                                <div class="product-image-container">
                                    <el-image :src="product.mainImageUrl && !product.mainImageUrl.startsWith('http') ? '/images/product/' + product.mainImageUrl : product.mainImageUrl || 
                                      (product.imageUrl && !product.imageUrl.startsWith('http') ? '/images/product/' + product.imageUrl : product.imageUrl) || 
                                      (product.coverImage && !product.coverImage.startsWith('http') ? '/images/product/' + product.coverImage : product.coverImage) || 
                                      (product.image && !product.image.startsWith('http') ? '/images/product/' + product.image : product.image) || 
                                      (product.imgUrl && !product.imgUrl.startsWith('http') ? '/images/product/' + product.imgUrl : product.imgUrl) || 
                                      (product.thumbnail && !product.thumbnail.startsWith('http') ? '/images/product/' + product.thumbnail : product.thumbnail) || 
                                      'https://placeholder.pics/svg/300/DEDEDE/555555/产品图片'" 
                            fit="cover" class="product-image" loading="lazy" />
                                    <div class="favorite-button" @click.stop="toggleFavorite(product)" :data-favorited="product.isFavorite">
                                        <el-icon :class="{ 'active': product.isFavorite }">
                                            <Star :style="{ color: product.isFavorite ? '#FF2D55' : '' }" />
                                        </el-icon>
                                    </div>
                                    <div class="product-badge" v-if="product.condition">
                                        <span>{{ product.condition }}</span>
                                    </div>
                                </div>
                                <div class="product-info">
                                    <h4 class="product-name">{{ product.name }}</h4>
                                    <p class="product-price">¥{{ product.price }}</p>
                                    
                                    <!-- 测试直接显示原始字段 -->
                                    <p class="product-description" v-if="product.description">
                                        {{ product.description }}
                                    </p>
                                    <p class="product-description" v-else-if="product.content">
                                        {{ product.content }}
                                    </p>
                                    <p class="product-description" v-else-if="product.title">
                                        {{ product.title }}
                                    </p>
                                    <p class="product-description" v-else>
                                        暂无描述
                                    </p>
                                    
                                    <div class="product-meta">
                                        <!-- 测试直接显示原始位置字段 -->
                                        <span class="product-location" v-if="product.school">
                                            <el-icon><Location /></el-icon>
                                            {{ product.school }}
                                        </span>
                                        <span class="product-location" v-else-if="product.location">
                                            <el-icon><Location /></el-icon>
                                            {{ product.location }}
                                        </span>
                                        <span class="product-location" v-else-if="product.locationDescription">
                                            <el-icon><Location /></el-icon>
                                            {{ product.locationDescription }}
                                        </span>
                                        <span class="product-location" v-else>
                                            <el-icon><Location /></el-icon>
                                            未知位置e
                                        </span>
                                        <span class="product-time">一个月内  </span>
                                        <!-- {{ formatTimeAgo( getNestedValue(product.createTime, 'createTime')) }} -->
                                    </div>
                                </div>
                            </div>
                        </div>
                        
                        <!-- 移动加载状态和底部提示到这里 -->
                        <div v-if="loadingMore" class="loading-more">
                            <el-skeleton :rows="1" animated />
                        </div>
                        <div v-if="noMoreData && products.length > 0" class="no-more-data">
                            已经到底啦 ~
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- 移动端筛选对话框 -->
        <el-dialog v-model="showFilterDialog" title="筛选条件" width="350px" class="ios-dialog">
            <div class="filter-options">
                <h4>价格区间</h4>
                <el-slider v-model="priceRange" range :min="0" :max="10000" :step="100" show-input
                    :format-tooltip="formatPrice" />
                
                <h4>商品状态</h4>
                <div class="condition-options">
                    <el-checkbox-group v-model="conditionFilter">
                        <el-checkbox label="全新">全新</el-checkbox>
                        <el-checkbox label="9成新">9成新</el-checkbox>
                        <el-checkbox label="8成新">8成新</el-checkbox>
                        <el-checkbox label="7成新及以下">7成新及以下</el-checkbox>
                    </el-checkbox-group>
                </div>
                
                <h4>学校</h4>
                <el-select v-model="schoolFilter" placeholder="选择学校" clearable class="full-width">
                    <el-option v-for="school in schoolOptions" :key="school.value" :label="school.label"
                        :value="school.value" />
                </el-select>
            </div>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="resetAllFilters" plain>重置</el-button>
                    <el-button type="primary" @click="applyFiltersAndCloseDialog">应用</el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, nextTick, onUnmounted, watch } from 'vue'
import { useRouter } from 'vue-router'
import * as ElementPlusIconsVue from '@element-plus/icons-vue'
import { Filter, Refresh, Location, School, ArrowDown, Check } from '@element-plus/icons-vue'
import request from '@/utils/request'
import { ElMessage } from 'element-plus'
import { useUserStore } from '@/stores/user'

// 调试：检查ElementPlusIconsVue导入
console.log('ElementPlusIconsVue:', ElementPlusIconsVue);

// 定义类型接口
interface Category {
    id: number;
    name: string;
  icon?: string;
    parentId?: number;
}

interface Product {
    id: number;
    name: string;
    price: number;
    mainImageUrl?: string;
  image?: string;
  imageUrl?: string;
  coverImage?: string;
  imgUrl?: string;
  thumbnail?: string;
    description?: string;
    content?: string;
  title?: string;
    categoryId?: number;
  category?: number;
    condition?: string;
    locationDescription?: string;
    location?: string;
  school?: string;
    createTime?: string;
    status?: string;
  views?: number;
  sellerName?: string;
  introduce?: string;
  isFavorite?: boolean;
}

const router = useRouter()

// 图标映射
const categoryIcons: { [key: string]: any } = {
    book: ElementPlusIconsVue.Reading,
    clothes: ElementPlusIconsVue.ShoppingBag,
    electronics: ElementPlusIconsVue.Monitor,
    sports: ElementPlusIconsVue.Basketball,
    daily: ElementPlusIconsVue.House,
    other: ElementPlusIconsVue.More
}

// 新增：辅助函数，用于更安全地获取分类图标组件
const getCategoryIconComponent = (iconName?: string) => {
  if (iconName && categoryIcons.hasOwnProperty(iconName)) {
    const iconComponent = categoryIcons[iconName];
    if (iconComponent) { // 进一步检查组件是否存在
        return iconComponent;
    } else {
        // 如果在映射中找到了键，但对应的值是undefined/null（理论上不应该发生，除非categoryIcons定义有问题）
        console.warn(`Icon component for key '${iconName}' is undefined in categoryIcons. Falling back to 'other'.`);
        return categoryIcons['other'];
    }
  }
  // 如果iconName未提供，或者在categoryIcons中没有对应的键，则使用默认图标
  if (iconName && !categoryIcons.hasOwnProperty(iconName)) {
    console.warn(`Icon key '${iconName}' not found in categoryIcons. Falling back to 'other'.`);
  }
  return categoryIcons['other'];
}

// 数据状态
const categories = ref<Category[]>([])
const products = ref<Product[]>([])
const loading = ref(false) // 改为默认不加载
const initialLoading = ref(true) // 初始加载状态
const categoriesLoading = ref(false)
const activeCategory = ref<string | number>(0)
const searchKeyword = ref('')
const sortBy = ref('newest')
const currentPage = ref(1)
const pageSize = ref(20)
const total = ref(0)
const noMoreData = ref(false) // 是否已加载全部数据
const loadingMore = ref(false) // 加载更多状态
const lastRequestTime = ref(0) // 上次请求时间，防止短时间内重复请求
const showFilterDialog = ref(false)
const priceRange = ref([0, 5000])
const conditionFilter = ref<string[]>([])
const schoolFilter = ref('')
const isFirstLoad = ref(true) // 是否是首次加载

// 学校选项
const schoolOptions = ref<{ value: string, label: string }[]>([])
const schoolsLoading = ref(false)

// 定义排序选项数组
const sortOptions = [
    { label: '最新发布', value: 'newest' },
    { label: '价格从低到高', value: 'priceAsc' },
    { label: '价格从高到低', value: 'priceDesc' },
    { label: '最受欢迎', value: 'mostViewed' }
];

// 下拉菜单状态
const showSchoolDropdown = ref(false);
const showConditionDropdown = ref(false);
const showSortDropdown = ref(false);

// 切换下拉菜单显示
const toggleSchoolDropdown = () => {
    showSchoolDropdown.value = !showSchoolDropdown.value;
    showConditionDropdown.value = false;
    showSortDropdown.value = false;
};

const toggleConditionDropdown = () => {
    showConditionDropdown.value = !showConditionDropdown.value;
    showSchoolDropdown.value = false;
    showSortDropdown.value = false;
};

const toggleSortDropdown = () => {
    showSortDropdown.value = !showSortDropdown.value;
    showSchoolDropdown.value = false;
    showConditionDropdown.value = false;
};

// 选择学校
const selectSchool = (value: string) => {
    schoolFilter.value = value;
    schoolSearchText.value = ''; // 清空搜索文本
    showSchoolDropdown.value = false;
    applyFilters();
};

// 选择排序方式
const handleSortSelect = (value: string) => {
    sortBy.value = value;
    showSortDropdown.value = false;
    fetchProducts();
};

// 模拟数据
const mockCategories = [
    { id: 1, name: '电子产品', icon: 'electronics' },
    { id: 7, name: '手机数码', icon: 'electronics', parentId: 1 },
    { id: 8, name: '电脑配件', icon: 'electronics', parentId: 1 },
    { id: 2, name: '图书教材', icon: 'book' },
    { id: 9, name: '课本教材', icon: 'book', parentId: 2 },
    { id: 10, name: '考试资料', icon: 'book', parentId: 2 },
    { id: 3, name: '生活用品', icon: 'daily' },
    { id: 4, name: '服装鞋帽', icon: 'clothes' },
    { id: 5, name: '运动健身', icon: 'sports' },
    { id: 6, name: '票券小物', icon: 'other' }
]

const mockProducts = [
    {
        id: 1,
        name: 'iPhone 13 Pro 256GB',
        price: 5999.00,
        mainImageUrl: 'https://img.yzcdn.cn/vant/ipad.jpeg',
        description: '全新未拆封，国行正品，面容ID，A15仿生芯片',
        categoryId: 7,
        condition: '全新',
        locationDescription: '北京大学',
        createTime: '2023-05-20T10:30:00',
        status: '在售',
        views: 138,
        isFavorite: false,
    },
    {
        id: 2,
        name: 'MacBook Pro M1 13英寸',
        price: 7999.00,
        mainImageUrl: 'https://img.yzcdn.cn/vant/apple-1.jpg',
        description: '2021年款，8+256GB，九成新，无磕碰，电池健康度95%',
        categoryId: 8,
        condition: '9成新',
        locationDescription: '清华大学',
        createTime: '2023-05-21T14:20:00',
        status: '在售',
        views: 96,
        isFavorite: true,
    },
    {
        id: 3,
        name: '微积分教材 第八版',
        price: 45.00,
        mainImageUrl: 'https://img.yzcdn.cn/vant/apple-2.jpg',
        description: '大一高数课本，有少量笔记，配套习题册已完成',
        categoryId: 9,
        condition: '8成新',
        locationDescription: '浙江大学',
        createTime: '2023-05-22T09:15:00',
        status: '在售',
        views: 42,
        isFavorite: false,
    },
    {
        id: 4,
        name: '耐克Air Force 1运动鞋',
        price: 599.00,
        mainImageUrl: 'https://img.yzcdn.cn/vant/cat.jpeg',
        description: '白色，42码，只穿过一次，几乎全新',
        categoryId: 4,
        condition: '9成新',
        locationDescription: '复旦大学',
        createTime: '2023-05-23T16:40:00',
        status: '在售',
        views: 64,
        isFavorite: false,
    },
    {
        id: 5,
        name: '考研政治真题集',
        price: 39.00,
        mainImageUrl: 'https://fastly.jsdelivr.net/npm/@vant/assets/apple-5.jpeg',
        description: '2023年考研政治真题解析，含答案和解题思路',
        categoryId: 10,
        condition: '全新',
        locationDescription: '中国人民大学',
        createTime: '2023-05-24T11:10:00',
        status: '在售',
        views: 89,
        isFavorite: false,
    },
    {
        id: 6,
        name: '小米手环7',
        price: 129.00,
        mainImageUrl: 'https://fastly.jsdelivr.net/npm/@vant/assets/apple-1.jpeg',
        description: '全功能正常，电池续航良好，赠送充电线',
        categoryId: 7,
        condition: '8成新',
        locationDescription: '北京大学',
        createTime: '2023-05-25T13:25:00',
        status: '在售',
        views: 37,
        isFavorite: false,
    },
    {
        id: 7,
        name: '宿舍收纳盒 三件套',
        price: 59.00,
        mainImageUrl: 'https://fastly.jsdelivr.net/npm/@vant/assets/apple-2.jpeg',
        description: '可折叠布艺收纳盒，适合宿舍使用，节省空间',
        categoryId: 3,
        condition: '全新',
        locationDescription: '清华大学',
        createTime: '2023-05-26T17:55:00',
        status: '在售',
        views: 50,
        isFavorite: false,
    },
    {
        id: 8,
        name: '篮球 斯伯丁正品',
        price: 199.00,
        mainImageUrl: 'https://fastly.jsdelivr.net/npm/@vant/assets/apple-3.jpeg',
        description: '标准7号比赛用球，室内外通用，手感好',
        categoryId: 5,
        condition: '9成新',
        locationDescription: '浙江大学',
        createTime: '2023-05-27T08:35:00',
        status: '在售',
        views: 28,
        isFavorite: false,
    },
    {
        id: 9,
        name: '哈利波特全集 英文原版',
        price: 399.00,
        mainImageUrl: 'https://fastly.jsdelivr.net/npm/@vant/assets/apple-4.jpeg',
        description: '全套7册，精装收藏版，几乎全新，仅拆封阅读过一次',
        categoryId: 2,
        condition: '9成新',
        locationDescription: '复旦大学',
        createTime: '2023-05-28T10:45:00',
        status: '在售',
        views: 73,
        isFavorite: false,
    },
    {
        id: 10,
        name: 'AirPods Pro 二代',
        price: 1299.00,
        mainImageUrl: 'https://img.yzcdn.cn/vant/apple-3.jpg',
        description: '苹果原装耳机，音质好，主动降噪，全新未拆封',
        categoryId: 7,
        condition: '全新',
        locationDescription: '中国人民大学',
        createTime: '2023-05-29T14:05:00',
        status: '在售',
        views: 104,
        isFavorite: false,
    },
    {
        id: 11,
        name: '显示器 27英寸 4K',
        price: 1599.00,
        mainImageUrl: 'https://img.yzcdn.cn/vant/apple-4.jpg',
        description: '三星显示器，4K高清，HDR，护眼不闪屏，99%sRGB色域',
        categoryId: 8,
        condition: '9成新',
        locationDescription: '北京大学',
        createTime: '2023-05-30T16:20:00',
        status: '在售',
        views: 62,
        isFavorite: false,
    },
    {
        id: 12,
        name: '自行车 山地车',
        price: 899.00,
        mainImageUrl: 'https://img.yzcdn.cn/vant/cat.jpeg',
        description: '21速变速，铝合金车架，前减震，9成新，附赠车锁',
        categoryId: 5,
        condition: '8成新',
        locationDescription: '清华大学',
        createTime: '2023-05-31T09:50:00',
        status: '在售',
        views: 48,
        isFavorite: false,
    }
]

// 计算属性
const currentCategory = computed(() => {
    return categories.value.find((c: Category) => c.id === Number(activeCategory.value))
})

const filteredProducts = computed(() => {
    return products.value;
})

// 请求数据
const fetchCategories = async () => {
    categoriesLoading.value = true
    try {
        const response = await request.get('/products/categories')
        // 正确处理返回的数据结构
        if (response.code === 200) {
            categories.value = response.data
            // 调试：打印后端返回的分类数据
            console.log('后端返回的分类数据:', JSON.stringify(response.data, null, 2));
            if (response.data && response.data.length > 0) {
                const firstCategory = response.data[0];
                console.log('第一个分类的icon值:', firstCategory.icon);
                console.log('categoryIcons映射中是否存在此icon键:', firstCategory.icon && categoryIcons.hasOwnProperty(firstCategory.icon));
                console.log('尝试从categoryIcons获取的组件:', firstCategory.icon && categoryIcons[firstCategory.icon]);
                console.log('通过getCategoryIconComponent获取的组件:', getCategoryIconComponent(firstCategory.icon));
            }
        } else {
            ElMessage.error(response.message || '获取分类失败')
            // 使用模拟数据
            categories.value = mockCategories
        }
        // 分类加载完成后自动开始加载商品
        if (isFirstLoad.value) {
            fetchProducts()
            isFirstLoad.value = false
        }
    } catch (error) {
        console.error('获取分类失败', error)
        // 使用模拟数据
        categories.value = mockCategories
        if (isFirstLoad.value) {
            fetchProducts()
            isFirstLoad.value = false
        }
    } finally {
        categoriesLoading.value = false
    }
}

const fetchProducts = async (loadMore = false) => {
    // 防止重复请求 - 如果当前正在加载或者距离上次请求不到500ms，则不发起新请求
    const now = Date.now()
    if ((loading.value || loadingMore.value) || 
        (now - lastRequestTime.value < 500 && !isFirstLoad.value)) {
        return
    }
    
    // 设置加载状态
    if (loadMore) {
        loadingMore.value = true
    } else {
        initialLoading.value = true
        loading.value = true
        currentPage.value = 1
        products.value = []
        noMoreData.value = false
    }
    
    lastRequestTime.value = now

    try {
        let url = '/products'
        const params: Record<string, any> = {
            // MyBatis-Plus从0开始，前端页码从1开始，发送请求时页码减1
            page: currentPage.value - 1, // 修改这里：页码减1
            limit: pageSize.value,
            sort: sortBy.value
        }

        // 添加 requestUserId 参数
        const userInfo = localStorage.getItem('userInfo');
        if (userInfo) {
            try {
                const parsedUserInfo = JSON.parse(userInfo);
                if (parsedUserInfo && parsedUserInfo.id) {
                    params.requestUserId = parsedUserInfo.id;
                }
            } catch (e) {
                console.error("解析用户信息失败:", e);
            }
        }
        
        // 记录日志帮助调试
        console.log(`发送请求：页码=${currentPage.value-1}，每页=${pageSize.value}，加载更多=${loadMore}`);
        
        // 其他参数保持不变
        if (activeCategory.value !== 0) {
            params.category = activeCategory.value
        }
        
        if (searchKeyword.value) {
            params.search = searchKeyword.value
        }
        
        if (priceRange.value[0] > 0 || priceRange.value[1] < 5000) {
            params.minPrice = priceRange.value[0]
            params.maxPrice = priceRange.value[1]
        }
        
        if (conditionFilter.value.length) {
            params.conditions = conditionFilter.value.join(',')
        }
        
        if (schoolFilter.value) {
            params.schools = schoolFilter.value
        }
        
        const response = await request.get(url, { params })
        
        // 正确处理返回的数据结构
        if (response.code === 200) {
            // 在处理API响应后，记录原始数据格式
            console.log('API响应结构:', response);
            
            // 如果有商品，检查第一个商品的结构
            if (response.data.content && response.data.content.length > 0) {
                console.log('API返回的商品数据示例:', response.data.content[0]);
            }
            
            // 商品数据在response.data.content中
            const newProducts = response.data.content || []
            
            // 处理新商品数据，确保所需字段存在
            const processedProducts = newProducts.map((product: any) => {
                // 确保所有关键字段存在，可以添加默认值或转换
                return {
                    ...product,
                    // 如果字段名与预期不同，可以在这里进行映射
                    description: product.description || product.introduce || product.content || product.title || '',
                    locationDescription: product.locationDescription || product.location || product.school || '',
                    // 处理图片URL字段，映射后端可能返回的不同图片字段
                    mainImageUrl: product.mainImageUrl || product.imageUrl || product.coverImage || product.image || product.imgUrl || product.thumbnail || '',
                    // 处理商品收藏状态，如果API返回了收藏状态则使用，否则默认为未收藏
                    isFavorite: product.isFavorite || product.favorited || false
                };
            });
            
            if (loadMore) {
                // 追加新数据
                products.value = [...products.value, ...processedProducts]
            } else {
                // 替换数据
                products.value = processedProducts
            }
            
            // 总数可能在response.data.data.totalElements或其他字段中
            total.value = response.data.totalElements || response.data.total || response.data.content?.length || 0
            
            // 检查是否已加载全部数据
            if (products.value.length >= total.value || newProducts.length === 0) {
                noMoreData.value = true
            } else {
                currentPage.value++ // 为下次加载准备
            }
            
            // 输出日志帮助调试
            console.log(`数据加载成功：当前${products.value.length}/${total.value}条，下次页码=${currentPage.value-1}`);
        } else {
            if (!loadMore) {
                // 只在首次加载失败时提示错误，避免滚动加载时频繁弹出提示
                ElMessage.error(response.message || '获取商品失败')
            }
            // 使用模拟数据
            useMockProducts(loadMore)
        }
    } catch (error) {
        console.error('获取商品失败', error)
        // 使用模拟数据
        useMockProducts(loadMore)
    } finally {
        loading.value = false
        initialLoading.value = false
        loadingMore.value = false
        
        // 初次加载完成后，检查是否需要立即加载更多
        if (!loadMore) {
            nextTick(() => {
                checkShouldLoadMore();
            });
        }
    }
}

// 使用模拟商品数据
const useMockProducts = (loadMore = false) => {
    loading.value = true
    initialLoading.value = false
    
    // 模拟分类产品加载延迟
    console.log('加载模拟商品数据')
    
    setTimeout(() => {
        const categoryProducts = mockProducts
        
        if (categoryProducts && categoryProducts.length > 0) {
            // 为所有商品添加随机的收藏状态（实际项目中应从API获取）
            categoryProducts.forEach(product => {
                if (typeof product.isFavorite === 'undefined') {
                    product.isFavorite = Math.random() > 0.7; // 随机设置30%的商品为已收藏状态
                }
            });
            
            processProducts(categoryProducts, loadMore)
        } else {
            products.value = []
            noMoreData.value = true
        }
        loading.value = false
    }, 500) // 模拟加载延迟
    }
    
// 添加 processProducts 函数的实现
const processProducts = (newProducts: Product[], loadMore = false) => {
    const processed = newProducts.map(product => ({
        ...product,
        description: product.description || product.introduce || product.content || product.title || '',
        locationDescription: product.locationDescription || product.location || product.school || '',
        mainImageUrl: product.mainImageUrl || product.imageUrl || product.coverImage || product.image || product.imgUrl || product.thumbnail || '',
        isFavorite: product.isFavorite === undefined ? (Math.random() > 0.8) : product.isFavorite, // 如果未定义则随机设置
    }));

    if (loadMore) {
        products.value = [...products.value, ...processed];
    } else {
        products.value = processed;
    }

    total.value = products.value.length; // 在模拟数据时，total可以简单地设置为当前产品数量
    // 或者，如果有一个预期的总数，可以这样设置：
    // total.value = mockProducts.length; 

    if (products.value.length >= mockProducts.length) { // 假设mockProducts包含所有可能的模拟商品
        noMoreData.value = true;
    } else {
        noMoreData.value = false;
        if (!loadMore) currentPage.value = 1; // 如果不是加载更多，重置页码
        currentPage.value++; // 为下次加载准备 (如果首页从1开始，则首次加载后应为2)
    }
    console.log(`processProducts: 当前${products.value.length}/${total.value}条`);
};

// 方法
const handleCategorySelect = (id: string | number) => {
    activeCategory.value = id
    fetchProducts()
}

const handleSearch = () => {
    fetchProducts()
}

const handleSort = (command: string) => {
    sortBy.value = command
    fetchProducts()
}

const getSortLabel = () => {
    switch (sortBy.value) {
        case 'newest': return '最新发布'
        case 'priceAsc': return '价格从低到高'
        case 'priceDesc': return '价格从高到低'
        case 'mostViewed': return '最多浏览'
        default: return '排序方式'
    }
}

const handleScroll = (event: Event) => {
    const container = event.target as HTMLElement
    const scrollTop = container.scrollTop
    const scrollHeight = container.scrollHeight
    const clientHeight = container.clientHeight
    
    console.log('滚动检测:', {
        scrollTop,
        scrollHeight,
        clientHeight,
        remaining: scrollHeight - scrollTop - clientHeight,
        loading: loading.value,
        loadingMore: loadingMore.value,
        noMoreData: noMoreData.value,
        productsCount: products.value.length,
        total: total.value
    });
    
    // 触发阈值从200px增加到300px，更容易触发
    if (scrollHeight - scrollTop - clientHeight < 300 && 
        !loading.value && !loadingMore.value && !noMoreData.value) {
        console.log('触发加载更多');
        loadMore();
    }
}

// 加载更多数据
const loadMore = () => {
    console.log('执行loadMore');
    if (!loading.value && !loadingMore.value && !noMoreData.value) {
        fetchProducts(true);
    }
}

const goToProduct = async (product: Product) => {
    try {
        // 显示加载状态
        loading.value = true;
        
        try {
            // 先尝试从API获取商品详情预加载到localStorage
            const response = await request.get(`/products/${product.id}`);
            
            if (response && (response.code === 200 || response.status === 200)) {
                // 预加载商品详情到localStorage
                const productDetail = response.data || response;
            localStorage.setItem('currentProductDetail', JSON.stringify(productDetail));
            localStorage.setItem('productDetailSource', 'api');
            localStorage.setItem('productDetailTimestamp', Date.now().toString());
        } else {
                console.log('商品详情预加载未成功，将由详情页面处理');
                // 清理旧数据，让详情页自行处理
            localStorage.removeItem('currentProductDetail');
            localStorage.removeItem('productDetailSource');
            localStorage.removeItem('productDetailTimestamp');
            }
            
            // 无论成功与否都会跳转，让商品详情页面自行处理数据获取
            router.push(`/product/${product.id}`);
    } catch (error) {
            console.error('商品详情预加载失败:', error);
            console.log('将由详情页面处理数据获取');
        
        // 清除可能存在的旧数据
        localStorage.removeItem('currentProductDetail');
        localStorage.removeItem('productDetailSource');
        localStorage.removeItem('productDetailTimestamp');
        
        // 出错时仍然跳转
        router.push(`/product/${product.id}`);
        } finally {
            // 恢复加载状态
            loading.value = false;
        }
    } finally {
        // 恢复加载状态
        loading.value = false;
    }
}

const handleProductClick = (product: Product, event: Event) => {
    // 提供点击反馈
    const productCard = event?.currentTarget as HTMLElement;
    if (productCard) {
        productCard.style.opacity = '0.7';
        setTimeout(() => {
            productCard.style.opacity = '1';
            goToProduct(product);
        }, 150);
    } else {
        goToProduct(product);
    }
}

const formatPrice = (val: number) => {
    return `¥${val}`
}

// 重置所有筛选条件
const resetAllFilters = () => {
    priceRange.value = [0, 5000]
    conditionFilter.value = []
    schoolFilter.value = ''
    fetchProducts() // 重新加载商品
}

// 应用筛选
const applyFilters = () => {
    // 每次应用筛选时重置加载状态，从第一页开始重新加载
    currentPage.value = 1
    noMoreData.value = false
    fetchProducts()
}

// 应用筛选并关闭对话框
const applyFiltersAndCloseDialog = () => {
    showFilterDialog.value = false
    fetchProducts()
}


// 安全获取嵌套属性
const getNestedValue = (obj, path) => {
    if (!obj) return undefined;
    const parts = path.split('.');
    let current = obj;
    for (const part of parts) {
        if (current == null || typeof current !== 'object') return undefined;
        current = current[part];
    }
    return current;
};

// 格式化时间为"几小时前"、"几天前"等形式
const formatTimeAgo = (dateStr) => {
    try {
        const now = new Date();
        const past = new Date(dateStr);
        const diffInSeconds = Math.floor((now - past) / 1000);
        
        if (diffInSeconds < 60) return `${diffInSeconds}秒前`;
        if (diffInSeconds < 3600) return `${Math.floor(diffInSeconds / 60)}分钟前`;
        if (diffInSeconds < 86400) return `${Math.floor(diffInSeconds / 3600)}小时前`;
        if (diffInSeconds < 2592000) return `${Math.floor(diffInSeconds / 86400)}天前`;
        if (diffInSeconds < 31536000) return `${Math.floor(diffInSeconds / 2592000)}个月前`;
        return `${Math.floor(diffInSeconds / 31536000)}年前`;
    } catch (e) {
        console.error('时间格式化错误:', e);
        return '未知时间';
    }
             
}

// 在组件中添加一个辅助函数，主动检查是否需要加载更多数据
const checkShouldLoadMore = () => {
    const container = document.querySelector('.product-grid-container');
    if (container) {
        const scrollTop = container.scrollTop;
        const scrollHeight = container.scrollHeight;
        const clientHeight = container.clientHeight;
        
        console.log('主动检查是否需要加载:', {
            scrollHeight,
            clientHeight,
            contentHeight: scrollHeight,
            visibleHeight: clientHeight,
            canLoadMore: !loading.value && !loadingMore.value && !noMoreData.value
        });
        
        // 如果内容高度不足以填充可视区域，且没有正在加载，且还有更多数据，则加载更多
        if (scrollHeight <= clientHeight * 1.2 && 
            !loading.value && !loadingMore.value && !noMoreData.value) {
            console.log('内容不足，自动加载更多');
            loadMore();
            return true;
        }
    }
    return false;
}

// 确保DOM更新后绑定事件监听
const attachScrollListener = () => {
    const productContainer = document.querySelector('.product-grid-container');
    console.log('找到滚动容器:', productContainer);
    if (productContainer) {
        // 先移除可能存在的旧监听器，避免重复
        productContainer.removeEventListener('scroll', handleScroll);
        // 添加新监听器
        productContainer.addEventListener('scroll', handleScroll);
        console.log('滚动监听器已添加');
        
        // 检查是否需要立即加载更多
        nextTick(() => {
            checkShouldLoadMore();
        });
    } else {
        // 如果未找到容器，延迟再试
        setTimeout(attachScrollListener, 500);
    }
};

// 监听窗口尺寸变化，在窗口调整后检查是否需要加载更多
window.addEventListener('resize', () => {
    nextTick(() => {
        checkShouldLoadMore();
    });
});

// 确保卸载组件时移除事件
onUnmounted(() => {
    const productContainer = document.querySelector('.product-grid-container');
    if (productContainer) {
        productContainer.removeEventListener('scroll', handleScroll);
    }
    
    window.removeEventListener('resize', updateFilterButtonBehavior);
    window.removeEventListener('resize', checkShouldLoadMore);
});

// 响应式区分筛选方式
onMounted(() => {
    // 点击其他区域关闭下拉菜单
    document.addEventListener('click', (e) => {
        const filterDropdowns = document.querySelectorAll('.filter-dropdown');
        let clickedInside = false;
        
        filterDropdowns.forEach(dropdown => {
            if (dropdown.contains(e.target as Node)) {
                clickedInside = true;
            }
        });
        
        if (!clickedInside) {
            showSchoolDropdown.value = false;
            showConditionDropdown.value = false;
            showSortDropdown.value = false;
        }
    });

    fetchCategories();
    fetchSchools();
    
    // 添加商品容器的滚动事件监听，确保在DOM更新后执行
    nextTick(() => {
        console.log('初始化滚动监听');
        attachScrollListener();
        
        // 添加响应式筛选按钮事件 - 在移动设备上显示筛选对话框
        window.addEventListener('resize', updateFilterButtonBehavior);
        updateFilterButtonBehavior();
    });
});

// 每次数据变化后，确保滚动监听器正确绑定
watch(products, () => {
    nextTick(attachScrollListener);
});

// 更新筛选按钮行为 - 在移动设备上使用对话框
const updateFilterButtonBehavior = () => {
    const filterButton = document.querySelector('.ios-filter-button')
    if (filterButton) {
        if (window.innerWidth <= 992) {
            // 在移动设备上，点击筛选按钮打开对话框
            filterButton.removeEventListener('click', resetAllFilters)
            filterButton.addEventListener('click', () => {
                showFilterDialog.value = true
            })
            // 修改按钮文字
            const buttonText = filterButton.querySelector('span')
            if (buttonText) {
                buttonText.textContent = '筛选'
            }
        } else {
            // 在桌面设备上，点击筛选按钮重置筛选条件
            filterButton.removeEventListener('click', () => {
                showFilterDialog.value = true
            })
            filterButton.addEventListener('click', resetAllFilters)
            // 修改按钮文字
            const buttonText = filterButton.querySelector('span')
            if (buttonText) {
                buttonText.textContent = '重置筛选'
            }
        }
    }
}

// 添加获取学校列表的函数
const fetchSchools = async () => {
    schoolsLoading.value = true
    try {
        const response = await request.get('/schools/list')
        if (response.code === 200) {
            // 转换后端数据为select选项格式
            schoolOptions.value = response.data.data.map((school: any) => ({
                value: school.name,
                label: school.name
            }))
            console.log('学校列表加载成功:', schoolOptions.value.length)
        } else {
            ElMessage.warning('获取学校列表失败，使用默认数据')
            // 后端获取失败时使用模拟数据
            schoolOptions.value = [
                { value: '北京大学', label: '北京大学' },
                { value: '清华大学', label: '清华大学' },
                { value: '浙江大学', label: '浙江大学' },
                { value: '复旦大学', label: '复旦大学' },
                { value: '中国人民大学', label: '中国人民大学' },
                { value: '上海交通大学', label: '上海交通大学' },
                { value: '南京大学', label: '南京大学' },
                { value: '武汉大学', label: '武汉大学' }
            ]
        }
    } catch (error) {
        console.error('获取学校列表失败', error)
        // 使用模拟数据
        schoolOptions.value = [
            { value: '北京大学', label: '北京大学' },
            { value: '清华大学', label: '清华大学' },
            { value: '浙江大学', label: '浙江大学' },
            { value: '复旦大学', label: '复旦大学' },
            { value: '中国人民大学', label: '中国人民大学' },
            { value: '上海交通大学', label: '上海交通大学' },
            { value: '南京大学', label: '南京大学' },
            { value: '武汉大学', label: '武汉大学' }
        ]
    } finally {
        schoolsLoading.value = false
    }
}

// 调整辅助函数 - 获取商品描述，修改优先级并增加调试日志
const getProductDescription = (product: Product): string => {
    // 输出完整商品对象，查看所有可用字段
    console.log('完整商品数据:', product);
    
    // 尝试所有可能的描述字段，按优先级排序
    const description = product.description || product.content || product.title || '';
    console.log(`商品 ${product.id} 描述:`, {
        原始描述: description,
        描述字段: product.description,
        内容字段: product.content,
        标题字段: product.title
    });
    
    return description;
}

// 调整辅助函数 - 获取商品位置，修改优先级
const getProductLocation = (product: Product): string => {
    // 调整位置字段的优先级，确保学校信息优先显示
    const location = product.school || product.location || product.locationDescription || '';
    
    // 不再使用分类名称作为位置信息
    console.log(`商品 ${product.id} 位置:`, {
        最终位置: location,
        学校: product.school,
        位置: product.location,
        位置描述: product.locationDescription,
        卖家: product.sellerName
    });
    
    return location;
}

// 在产品数据加载完成后，输出完整的样本数据
watch(() => products.value, (newProducts) => {
    if (newProducts.length > 0) {
        console.log('第一个商品完整数据:', JSON.stringify(newProducts[0], null, 2));
        console.log('产品数据所有字段:', Object.keys(newProducts[0]));
        
        // 检查图片URL字段
        console.log('图片URL检查:', {
            mainImageUrl: newProducts[0].mainImageUrl,
            image: newProducts[0].image,
            imageUrl: newProducts[0].imageUrl,
            coverImage: newProducts[0].coverImage,
            imgUrl: newProducts[0].imgUrl,
            thumbnail: newProducts[0].thumbnail
        });
        
        // 检查所有商品是否都缺少描述和位置
        const hasDescriptions = newProducts.filter((p: Product) => 
            p.description || p.content || p.title).length;
        const hasLocations = newProducts.filter((p: Product) => 
            p.school || p.location || p.locationDescription).length;
        
        console.log(`数据质量检查: ${hasDescriptions}/${newProducts.length} 件商品有描述, ${hasLocations}/${newProducts.length} 件商品有位置信息`);
    }
});

// 学校搜索
const schoolSearchText = ref('');
const filteredSchools = computed(() => {
    if (!schoolSearchText.value) {
        return schoolOptions.value;
    }
    return schoolOptions.value.filter(school => 
        school.label.toLowerCase().includes(schoolSearchText.value.toLowerCase())
    );
});

// 过滤学校列表
const filterSchools = () => {
    // 当输入时自动过滤，不需要额外操作
};

// 应用学校搜索
const applySchoolSearch = () => {
    if (schoolSearchText.value && filteredSchools.value.length === 0) {
        // 如果输入了学校名称但没有匹配的选项，使用输入的文本作为学校筛选条件
        schoolFilter.value = schoolSearchText.value;
        showSchoolDropdown.value = false;
        applyFilters();
    } else if (filteredSchools.value.length === 1) {
        // 如果只有一个匹配项，自动选择
        selectSchool(filteredSchools.value[0].value);
    }
};

// 商品状态选项
const conditionOptions = ['全新', '9成新', '8成新', '7成新及以下'];

// 获取商品状态显示文本
const getConditionLabel = () => {
    if (conditionFilter.value.length === 0) {
        return '商品状态';
    } else if (conditionFilter.value.length === 1) {
        return conditionFilter.value[0];
    } else {
        return `已选择${conditionFilter.value.length}项`;
    }
};

// 切换商品状态选项
const toggleConditionOption = (option: string) => {
    const index = conditionFilter.value.indexOf(option);
    if (index > -1) {
        conditionFilter.value.splice(index, 1);
    } else {
        conditionFilter.value.push(option);
    }
    applyFilters();
};

// 清除商品状态筛选
const clearConditionFilter = () => {
    conditionFilter.value = [];
    applyFilters();
};

// 添加切换收藏状态的函数
const toggleFavorite = async (product: Product) => {
    try {
        // 产品ID不存在时不进行操作
        if (!product.id) {
            ElMessage.error('商品信息不完整，无法收藏');
            return;
        }

        // 检查用户是否已登录
        const userInfo = localStorage.getItem('userInfo');
        const token = localStorage.getItem('token');
        if (!userInfo || !token) {
            ElMessage.warning('请先登录后再收藏商品');
            router.push('/login?redirect=' + encodeURIComponent(router.currentRoute.value.fullPath));
            return;
        }

        // 获取当前用户ID
        const parsedUserInfo = JSON.parse(userInfo);
        const userId = parsedUserInfo.id;
        
        if (!userId) {
            ElMessage.warning('请先登录后再收藏商品');
            return;
        }

        // 判断当前是否已收藏
        const isFavorited = product.isFavorite;
        
        // 根据当前状态决定是收藏还是取消收藏
        let response;
        if (isFavorited) {
            // 取消收藏
            response = await request.delete(`/products/${product.id}/favorite?userId=${userId}`, {
                headers: {
                    'Authorization': `Bearer ${token}`
                }
            });
        } else {
            // 添加收藏
            response = await request.post(`/products/${product.id}/favorite`, { userId }, {
                headers: {
                    'Authorization': `Bearer ${token}`
                }
            });
        }

        // 检查响应是否成功
        if (response && (response.code === 200 || response.status === 200)) {
            // 更新商品的收藏状态
            product.isFavorite = !isFavorited;
            
            // 提示用户操作结果
            ElMessage.success(isFavorited ? '已取消收藏' : '收藏成功');
        } else {
            // 操作失败
            ElMessage.error(response?.message || (isFavorited ? '取消收藏失败' : '收藏失败'));
        }
    } catch (error) {
        console.error('收藏操作失败:', error);
        ElMessage.error('操作失败，请稍后重试');
    }
};
</script>

<style scoped>
/* Ensure html and body don't interfere if possible within scope */
/* Note: Scoped styles might not affect html/body directly. Ensure no global styles override this. */

.ios-category-page {
    display: flex;
    flex-direction: column;
    height: 90vh; /* Fixed height for the entire page */
    width: 100%;
    background-color: #f6f6f6;
    --panel-background: #fff;
    --panel-border-radius: 16px;
    --panel-spacing: 16px;
    --panel-inner-spacing: 20px;
    --text-primary: #333;
    --text-secondary: #666;
    --active-color: #1990ff;
    --border-color: #e6e6e6;
    --button-background: #f5f5f5;
    color: var(--text-primary);
    overflow: hidden; /* Prevent the whole page from scrolling */
}

.ios-container {
    width: 90%;
    max-width: 1280px;
    margin: 0 auto;
    padding: 20px 0;
    flex-grow: 1; /* Let flexbox determine height */
    display: flex;
    flex-direction: column;
    overflow: hidden; /* Prevent this container from scrolling */
    min-height: 0; /* Fix potential flexbox overflow issue */
}

.ios-row {
    display: flex;
    margin: 0 -8px;
    flex: 1; /* Let this row fill the container */
    overflow: hidden; /* Prevent this row from scrolling */
    min-height: 0; /* Fix potential flexbox overflow issue */
}

/* 左侧栏样式 */
.ios-sidebar {
    flex: 0 0 280px; /* Fixed width */
    padding: 0 8px;
    overflow-y: hidden; /* Prevent sidebar from scrolling */
    max-height: 100%; /* Constrain height */
    min-height: 0; /* Fix potential flexbox overflow issue */
    /* Ensure the panel inside doesn't cause overflow if possible */
    display: flex; /* Use flex to manage the panel inside */
    flex-direction: column;
}

.ios-panel {
    background-color: var(--panel-background);
    border-radius: var(--panel-border-radius);
    /* Remove margin-bottom if sidebar is not scrolling */
    /* margin-bottom: var(--panel-spacing); */ 
    padding: var(--panel-inner-spacing);
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
    flex: 1; /* Allow panel to fill sidebar */
    overflow: hidden; /* Hide panel overflow if necessary */
    display: flex; /* Use flex for internal layout */
    flex-direction: column;
}

.panel-header, .filter-header {
    margin-bottom: 12px;
}

.panel-header h3, .filter-header h3 {
    margin: 0;
    font-size: 18px;
    font-weight: 600;
}

.filter-header h3 {
    font-size: 16px;
}

/* 分类列表样式 - Ensure it doesn't force scroll */
.ios-category-list {
   /* No specific height, let flexbox manage */
   overflow: hidden; /* Hide overflow */
   flex-shrink: 1; /* Allow shrinking if needed */
}

.category-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(60px, 1fr));
    gap: 8px;
}

.ios-category-item {
    display: flex;
    flex-direction: column;
    align-items: center;
    padding: 8px 4px;
    cursor: pointer;
    border-radius: 8px;
    transition: all 0.2s;
    text-align: center;
}

.ios-category-item:hover {
    background-color: rgba(0, 0, 0, 0.04);
}

.ios-category-item.active {
    background-color: rgba(25, 144, 255, 0.1);
    color: var(--active-color);
}

.category-icon {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 40px;
    height: 40px;
    margin-bottom: 6px;
    border-radius: 50%;
    background-color: rgba(0, 0, 0, 0.04);
}

.active .category-icon {
    background-color: rgba(25, 144, 255, 0.2);
}

.category-name {
    font-size: 12px;
    line-height: 1.3;
    /* 超长文本截断 */
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    width: 100%;
}

/* 筛选部分样式 */
.divider {
    height: 1px;
    background-color: var(--border-color);
    margin: 16px 0;
}

.filter-section-compact {
    margin-bottom: 12px;
}

.price-range-display {
    display: flex;
    justify-content: space-between;
    margin-top: 8px;
    color: var(--text-secondary);
    font-size: 14px;
}

.divider-text {
    margin: 0 5px;
}

.condition-options .el-checkbox {
    margin-right: 8px;
    margin-bottom: 8px;
}

.condition-grid {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 10px;
}

.full-width {
    width: 100%;
}

/* 右侧内容区样式 */
.ios-main-content {
    flex: 1; /* Take remaining horizontal space */
    padding: 0 8px;
    display: flex;
    flex-direction: column;
    overflow: hidden; /* Prevent this main area from scrolling */
    min-height: 0; /* Fix potential flexbox overflow issue */
    min-width: 0; /* Fix potential flexbox overflow issue */
}

.ios-search-bar {
    display: flex;
    align-items: center;
    margin-bottom: 16px;
    flex-wrap: wrap;
    gap: 12px;
    flex-shrink: 0; /* Prevent search bar from shrinking or growing */
}

.search-input-wrapper {
    flex: 1;
    min-width: 240px;
}

.ios-search-input {
    width: 100%;
}

.ios-search-input :deep(.el-input__wrapper) {
    border-radius: 8px;
    background-color: rgba(0, 0, 0, 0.03);
    padding-right: 12px;
    box-shadow: none !important;
}

.ios-search-input :deep(.el-input__inner) {
    height: 38px;
}

.filter-actions {
    display: flex;
    gap: 12px;
    align-items: center;
    flex-wrap: wrap;
}

.filter-select {
    width: 140px;
}

.ios-dropdown-trigger {
    height: 38px;
    padding: 0 16px;
    background-color: var(--button-background);
    border-radius: 8px;
    display: flex;
    align-items: center;
    cursor: pointer;
    transition: background-color 0.2s;
}

.ios-dropdown-trigger:hover {
    background-color: rgba(0, 0, 0, 0.05);
}

.ios-dropdown-trigger span {
    margin-right: 6px;
    font-size: 14px;
}

.ios-filter-button {
    height: 40px;
    background-color: var(--button-background);
    border-radius: 8px;
    padding: 0 15px;
    display: flex;
    align-items: center;
    cursor: pointer;
    transition: background-color 0.2s;
}

.ios-filter-button:hover {
    background-color: rgba(0, 0, 0, 0.05);
}

.ios-filter-button .el-icon {
    margin-right: 5px;
    font-size: 16px;
}

.ios-filter-button span {
    font-size: 15px;
}

/* 标题和结果统计 */
.ios-content-header {
    display: flex;
    align-items: baseline;
    margin-bottom: 20px;
    flex-shrink: 0; /* Prevent header from shrinking or growing */
}

.ios-content-header h2 {
    margin: 0;
    font-size: 24px;
    font-weight: 600;
}

.result-count {
    margin-left: 12px;
    color: var(--text-secondary);
    font-size: 14px;
}

/* 商品网格 */
.loading-container, .empty-container {
    flex-shrink: 0; /* Don't allow these to affect flex layout */
    padding: 20px 0;
}

.product-grid-container {
    flex: 1; /* Allow grid to take remaining vertical space */
    overflow-y: auto; /* Make ONLY this container scrollable vertically */
    padding-right: 5px;
    /* iOS风格的滚动条 */
    -webkit-overflow-scrolling: touch;
    scrollbar-width: thin;
    min-height: 0; /* Fix potential flexbox overflow issue */
}

.product-grid-container::-webkit-scrollbar {
    width: 6px;
}

.product-grid-container::-webkit-scrollbar-thumb {
    background-color: rgba(0, 0, 0, 0.2);
    border-radius: 3px;
}

.ios-product-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(240px, 1fr));
    gap: 16px;
    margin-bottom: 20px;
}

.ios-product-card {
    background-color: var(--panel-background);
    border-radius: var(--panel-border-radius);
    overflow: hidden;
    transition: transform 0.2s, box-shadow 0.2s;
    cursor: pointer;
}

.ios-product-card:hover {
    transform: translateY(-3px);
    box-shadow: 0 6px 16px rgba(0, 0, 0, 0.08);
}

.product-image-container {
    position: relative;
    padding-top: 75%; /* 4:3 Aspect Ratio */
    width: 100%;
}

.product-image {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
}

.favorite-button {
    position: absolute;
    top: 12px;
    right: 12px;
    width: 32px;
    height: 32px;
    border-radius: 50%;
    background-color: rgba(255, 255, 255, 0.8);
    backdrop-filter: blur(4px);
    display: flex;
    justify-content: center;
    align-items: center;
    color: #8E8E93;
    cursor: pointer;
    opacity: 0;
    transform: translateY(-5px);
    transition: all 0.25s ease;
    z-index: 10; /* 确保在图片上方 */
}

.ios-product-card:hover .favorite-button {
    opacity: 1;
    transform: translateY(0);
}

/* 已收藏状态的样式 */
.favorite-button.active,
.ios-product-card .favorite-button[data-favorited="true"] {
    opacity: 1;
    color: #FF2D55; /* 高亮红色表示已收藏 */
    transform: translateY(0);
}

.favorite-button:hover {
    background-color: rgba(255, 255, 255, 0.9);
    color: #FF2D55;
    transform: scale(1.1); /* 鼠标悬停时稍微放大 */
}

.product-badge {
    position: absolute;
    top: 10px;
    left: 10px;
    background-color: rgba(25, 144, 255, 0.9);
    color: white;
    padding: 3px 8px;
    border-radius: 4px;
    font-size: 12px;
    backdrop-filter: blur(4px);
    -webkit-backdrop-filter: blur(4px);
}

.product-info {
    padding: 14px;
}

.product-name {
    margin: 0 0 6px;
    font-size: 16px;
    font-weight: 600;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
}

.product-price {
    color: #ff4d4f;
    font-size: 18px;
    font-weight: 600;
    margin: 0 0 10px;
}

.product-description {
    color: var(--text-secondary);
    font-size: 13px;
    margin: 0 0 10px;
    line-height: 1.4;
    height: 36px;
    overflow: hidden;
    text-overflow: ellipsis;
    display: -webkit-box;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
}

.product-meta {
    display: flex;
    justify-content: space-between;
    align-items: center;
    font-size: 12px;
    color: var(--text-secondary);
}

.product-location {
    display: flex;
    align-items: center;
}

.product-location .el-icon {
    margin-right: 4px;
    font-size: 14px;
}

.product-time {
    white-space: nowrap;
}

/* 加载更多和无更多数据样式 */
.loading-more, .no-more-data {
    text-align: center;
    padding: 15px 0;
    color: var(--text-secondary);
    font-size: 14px;
    flex-shrink: 0; /* Prevent from affecting layout */
    /* 使其贴近底部 */
    margin-top: 10px;
}

/* 空状态样式 */
.empty-container {
    padding: 40px 0;
    display: flex;
    flex-direction: column;
    align-items: center;
}

/* 移动端适配 */
@media (max-width: 992px) {
    .ios-container {
        width: 95%;
        padding: 15px 0;
    }
    
    .ios-row {
        flex-direction: column;
    }
    
    .ios-sidebar {
        flex: none;
        width: 100%;
        margin-bottom: 16px;
    }
    
    .ios-category-list {
        max-height: unset;
        overflow-y: unset;
    }
    
    .ios-content-header {
        flex-direction: column;
        align-items: flex-start;
    }
    
    .result-count {
        margin-left: 0;
        margin-top: 4px;
    }
    
    .product-grid-container {
        max-height: unset;
        overflow-y: unset;
    }
}

/* 筛选对话框样式 */
.ios-dialog :deep(.el-dialog__header) {
    margin: 0;
    padding: 16px 20px;
    border-bottom: 1px solid var(--border-color);
}

.ios-dialog :deep(.el-dialog__headerbtn) {
    top: 16px;
    }
    
.ios-dialog :deep(.el-dialog__body) {
    padding: 20px;
    }

.ios-dialog :deep(.el-dialog__footer) {
    padding: 10px 20px 20px;
}

.filter-options h4 {
    margin: 0 0 12px;
    font-size: 16px;
    font-weight: 500;
}

.filter-options > div {
    margin-bottom: 24px;
}

.dialog-footer {
    display: flex;
    justify-content: flex-end;
    gap: 12px;
}

.category-loading {
    min-height: 150px;
}

/* 学校下拉菜单样式 */
.school-select-dropdown :deep(.el-scrollbar__view) {
    padding: 5px 0;
}

.school-option {
    display: flex;
    align-items: center;
    gap: 6px;
}

.school-option-icon {
    color: var(--active-color);
}

/* 学校选择器前缀图标 */
.school-icon {
    color: var(--active-color);
}

/* 下拉筛选菜单样式 */
.filter-dropdown {
    position: relative;
    z-index: 10;
}

.filter-dropdown-header {
    height: 40px;
    min-width: 120px;
    padding: 0 15px;
    background-color: var(--button-background);
    border-radius: 8px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    cursor: pointer;
    transition: background-color 0.2s;
}

.filter-dropdown-header:hover {
    background-color: rgba(0, 0, 0, 0.05);
}

.filter-dropdown-header span {
    font-size: 15px;
}

.filter-dropdown-header .el-icon {
    font-size: 14px;
}

.filter-dropdown-header .school-icon {
    margin-right: 5px;
    color: var(--active-color);
    font-size: 16px;
}

.filter-dropdown-content {
    position: absolute;
    top: 100%;
    left: 0;
    width: 220px;
    max-height: 300px;
    overflow-y: auto;
    margin-top: 8px;
    background-color: white;
    border-radius: 12px;
    box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1);
    padding: 8px;
    z-index: 20;
}

.filter-option {
    padding: 10px 15px;
    border-radius: 8px;
    margin: 4px 0;
    cursor: pointer;
    transition: all 0.2s;
    color: #606266;
    font-size: 15px;
}

.filter-option:hover {
    background-color: #f5f7fa;
}

.filter-option.active {
    background-color: #007AFF;
    color: white;
    font-weight: 500;
}

.filter-option-group {
    padding: 8px;
    display: flex;
    flex-direction: column;
    gap: 10px;
}

.filter-option-group .el-checkbox {
    margin-right: 0;
    width: 100%;
    padding: 6px 10px;
    border-radius: 6px;
    font-size: 15px;
}

.filter-option-group .el-checkbox:hover {
    background-color: #f5f7fa;
}

.search-input-container {
    padding: 8px;
    margin-bottom: 5px;
    border-bottom: 1px solid #f0f0f0;
}

.search-input-container .el-input__wrapper {
    border-radius: 6px;
    box-shadow: 0 0 0 1px #dcdfe6 inset;
}

.search-input-container .el-input__inner {
    height: 32px;
    font-size: 14px;
}

.option-with-check {
    display: flex;
    align-items: center;
    gap: 6px;
}

.check-icon {
    color: var(--active-color);
}
</style>

